package com.citcc.api.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.LinkedList;
import java.util.List;


/**
 * 公共路线接口方法，计算实际距离。
 */
public class MapDistanceUtil {

    private static final String HOSTARR = "http://restapi.amap.com/v3/geocode/regeo";
    private static final String HOST = "https://restapi.amap.com/v3/distance";
    //    private static final String HOST = "http://122.114.79.163:7770/v3/distance";
    private static final String KEY = "761e73b6188fb868feee5b558dcbcd7a";

    /**
     * 参数:（出发点数组、目的点）  格式：经度,纬度 ,type:0直线 1驾车 2公交 3步行
     * 返回: {
     * "status": "1",
     * "info": "OK",
     * "infocode": "10000",
     * "results": [{   //结果数组
     * "origin_id": "1",       //第一个起点
     * "dest_id": "1",         //目的地
     * "distance": "261278",  //距离（米）
     * "duration": "14280"    //预计时间（秒）
     * }]
     * }
     */
    public static String mapDistanceMethod(String[] origins, String destination, String type) {
        String responseEntity = null;
        for (int i = 0; i < 5 && responseEntity == null; i++) {
            responseEntity = mapDistance(origins, destination, type);
        }
        return responseEntity;
    }

    private static String mapDistance(String[] origins, String destination, String type) {
        StringBuilder originBuilder = new StringBuilder();
        for (int i = 0; i < origins.length; i++) {
            originBuilder.append(origins[i]);
            if (i < origins.length - 1) {
                originBuilder.append("|");
            }
        }
        List<NameValuePair> list = new LinkedList<>();
        list.add(new BasicNameValuePair("key", KEY));
        list.add(new BasicNameValuePair("output", "JSON"));
        list.add(new BasicNameValuePair("origins", originBuilder.toString()));
        list.add(new BasicNameValuePair("destination", destination));
        list.add(new BasicNameValuePair("type", type));
        String responseEntity = null;
        try {
            HttpGet httpGet = new HttpGet(new URIBuilder(HOST).setParameters(list).build());
            httpGet.setConfig(RequestConfig.custom().setConnectTimeout(2000).build());
            HttpResponse response = HttpClients.createDefault().execute(httpGet);
            responseEntity = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            if (e instanceof ConnectTimeoutException) {
                System.out.println("-------请求超时-------");
            } else {
                e.printStackTrace();
            }
        }
        return responseEntity;
    }

    public static String getLocationAddr(String location) {
        List<NameValuePair> list = new LinkedList<>();
        list.add(new BasicNameValuePair("key", KEY));
        list.add(new BasicNameValuePair("output", "JSON"));
        list.add(new BasicNameValuePair("location", location));
        String responseEntity = null;
        String addr = "";
        try {
            HttpGet httpGet = new HttpGet(new URIBuilder(HOSTARR).setParameters(list).build());
            httpGet.setConfig(RequestConfig.custom().setConnectTimeout(2000).build());
            HttpResponse response = HttpClients.createDefault().execute(httpGet);
            responseEntity = EntityUtils.toString(response.getEntity(), "UTF-8");
            JSONObject jsonObject = JSON.parseObject(responseEntity);
            addr = jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent")
                    .getJSONObject("building").getString("name");
            if (addr.equals("[]")) {
                addr = jsonObject.getJSONObject("regeocode").getString("formatted_address");
                if (addr.indexOf("省") > 0) {
                    addr = addr.substring(addr.indexOf("省") + 1, addr.length());
                }
                if (addr.indexOf("市") > 0) {
                    addr = addr.substring(addr.indexOf("市") + 1, addr.length());
                }
            }
        } catch (Exception e) {
            if (e instanceof ConnectTimeoutException) {
                System.out.println("-------请求超时-------");
            } else {
                e.printStackTrace();
            }
        }
        return addr;
    }

}
